#include "bsp_can.h"

uint8_t canRxBuff[8], canTxBuff[8];
CAN_TxHeaderTypeDef hcantx;
CAN_RxHeaderTypeDef hcanrx;
CAN_TxHeaderTypeDef hcantx2;
CAN_RxHeaderTypeDef hcanrx2;

/**
 * @brief  配置滤波器
 * @param  void
 * @retval void
 */
void CAN_ConfigFilter(void)
{
	CAN_FilterTypeDef sConfigFilter;
	
	sConfigFilter.FilterActivation = CAN_FILTER_ENABLE;	
	sConfigFilter.FilterBank = 0;
	sConfigFilter.SlaveStartFilterBank = 14;
	sConfigFilter.FilterFIFOAssignment = CAN_RX_FIFO0;
	sConfigFilter.FilterMode 	= CAN_FILTERMODE_IDMASK;
	sConfigFilter.FilterScale = CAN_FILTERSCALE_32BIT;
	sConfigFilter.FilterIdHigh 	= 0x00;
	sConfigFilter.FilterIdLow 	= 0x00;
	sConfigFilter.FilterMaskIdHigh 	= 0x00;
	sConfigFilter.FilterMaskIdLow 	= 0x00;
	
	if ( HAL_CAN_ConfigFilter(&hcan1, &sConfigFilter) != HAL_OK) {
		Error_Handler();
	}
	
	sConfigFilter.FilterBank = 14;
	
//	if ( HAL_CAN_ConfigFilter(&hcan2, &sConfigFilter) != HAL_OK) {
//		Error_Handler();
//	}
	
	if ( HAL_CAN_Start(&hcan1) != HAL_OK) {	
		Error_Handler();
	}
//	if ( HAL_CAN_Start(&hcan2) != HAL_OK) {	
//		Error_Handler();
//	}
	
	if ( HAL_CAN_ActivateNotification(&hcan1, CAN_IT_RX_FIFO0_MSG_PENDING|CAN_IT_RX_FIFO1_MSG_PENDING) != HAL_OK) {	
		Error_Handler();
	}
	
//	if ( HAL_CAN_ActivateNotification(&hcan2, CAN_IT_RX_FIFO0_MSG_PENDING|CAN_IT_RX_FIFO1_MSG_PENDING) != HAL_OK) {	
//		Error_Handler();
//	}
}

void bspcan_init(void)
{
	CAN_ConfigFilter();
}

extern void can_motor_updata(uint32_t StdId, uint8_t *rxbuff);
/**
 * @brief  CAN FIFO接收中断
 * @param  void
 * @retval void
 */
void HAL_CAN_RxFifo0MsgPendingCallback(CAN_HandleTypeDef *hcan)
{
	if ( hcan == &hcan1 ) {
		HAL_CAN_GetRxMessage(&hcan1, CAN_RX_FIFO0, &hcanrx, canRxBuff);
		can_motor_updata(hcanrx.StdId, canRxBuff);
	}	
	
//	if ( hcan == &hcan2 ) {
//		HAL_CAN_GetRxMessage(&hcan2, CAN_RX_FIFO0, &hcanrx, canRxBuff);
//		can_motor_updata(hcanrx.StdId, canRxBuff);
//	}	
}

/**
 * @brief  CAN发送一帧数据
 * @param  void
 * @retval void
 */
void can1_SendPacket(uint8_t *data, uint16_t addr)
{
	uint32_t txaddr;
	hcantx.StdId = addr;
	hcantx.IDE = CAN_ID_STD;
	hcantx.RTR = CAN_RTR_DATA;
	hcantx.DLC = 8;
	
	HAL_CAN_AddTxMessage(&hcan1, &hcantx, data, &txaddr);
}

/**
 * @brief  CAN发送一帧数据
 * @param  void
 * @retval void
 */
void can2_SendPacket(uint8_t *data, uint16_t addr)
{
	uint32_t txaddr;
	hcantx2.StdId = addr;
	hcantx2.IDE = CAN_ID_STD;
	hcantx2.RTR = CAN_RTR_DATA;
	hcantx2.DLC = 8;
	
//	HAL_CAN_AddTxMessage(&hcan2, &hcantx2, data, &txaddr);
}

/******************* (C) COPYRIGHT 2023 FUYEBING*****END OF FILE************/
